using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using SSharing.Frameworks.NetCore.Common.Consts;
using SSharing.Frameworks.NetCore.Common.Results;

namespace KwaiXiaoDian.OpenApi.Filters
{
    /// <summary>
    /// 异常处理过滤器
    /// </summary>
    public class ExceptionHandlerFilter : IExceptionFilter
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        public void OnException(ExceptionContext context)
        {
            //异常处理
            var ex = context.Exception;
            if (ex != null)
            {
                var logger = context.HttpContext.RequestServices.GetService<ILogger<ExceptionHandlerFilter>>();
                logger.LogError(ex, ex.Message);

                context.HttpContext.Response.StatusCode = StatusCodes.Status500InternalServerError;
                context.Result = new JsonResult(new ApiResult(ErrorCodeConst.B0001, ex.Message));
            }
        }
    }
}
